/* Create a new block of memory and do vital error checking.
*  The return value should be free'd by the calling function.
*/
#include "libutil.h"


/* Parse a file, one character at a time and return the current
 * word or non-word. The variable currw tracks whether the previous
 * return value was a word or non-word */
char *parse_file_char (FILE *data_file, int *currw)
{ 

  char *st = (char*)safe_malloc(MAX_WORD_LEN * sizeof(char));
  int len = 0; /*length of st*/
  char c;

  if ( data_file == NULL )
  {
     fprintf(stderr, "IO error, please check the filename\n");
     exit(-1);
  } 
  
  if ( ( c = fgetc(data_file)) == EOF )
    return NULL;
  else
    ungetc(c, data_file);


  /* 1 is word, 0 is non-word*/
  if( *currw == WORD )
  {
    while( (c = fgetc(data_file) ) != EOF && !isalpha(c) )
    {
       st[len++] = c; 
       if( len >= MAX_WORD_LEN )
       {
          st = (char*)safe_realloc( st, REALLOC_INCREMENT + MAX_WORD_LEN ); 
       } 
    }
    st[len] = '\0';
    if ( c != EOF )
     ungetc(c, data_file);
   
    *currw = NON_WORD; 
  } 
  else
  {
    while( (c = fgetc(data_file) ) != EOF && isalpha(c) )
    {
       st[len++] = c; 
       if( len >= MAX_WORD_LEN )
       {
          st = (char*)safe_realloc( st, REALLOC_INCREMENT + MAX_WORD_LEN ); 
       } 
    }
    st[len] = '\0';
    if( c != EOF )
     ungetc(c, data_file);
    *currw = WORD; 
  }  
  return st;
}

void *safe_malloc(size_t size)
{

  void *foo = malloc(size);
  if( !foo )
  {
    perror("Error!\n");
    exit(-1);
  }
  return foo;
}

/* Resize a pre-existing block of memory and do vital error checking.
*  The return value should be free'd by the calling function.
*/
void *safe_realloc(void *old_mem, size_t new_size)
{
  void *foo = realloc(old_mem, new_size); 
   
  if( !foo )
  {
    perror("Error!\n");
    exit(-1);
  }
  return foo;
}

/*Take a current string and create a new copy. The 
* return value should be free'd by the calling function.
*/
char *safe_strdup(const char *str)
{
  int len;
  char *st;

  len = strlen(str);
  st = calloc(len, sizeof(char));
  if( st == NULL )
    return NULL;

  return  strcpy(st, str); 
  
}
